#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/22  20:09
# @Author: 余浪人
# @email: yulangren520@gmail.com
import requests, base64, os, json
from datetime import datetime
from flask_login import login_required
from flask_mail import Message, Mail
from apps.control import sys_bp
from Crypto.PublicKey import RSA
from Crypto import Random
from flask import render_template, request, jsonify, current_app, abort
from apps.forms.synthesize_form import TL_Connector_Form, TL_WebApp_Form, TL_Email_Form, TL_Indexes_Form, TL_ThemePush_Form
from apps.lib.cache_sys import cache
from apps.lib.token import generate_token, Verify_authorization
from apps.models.content_model import TL_Content_Model
from apps.models.synthesize_model import TL_Connector_Model, TL_WebApp_Model, db, TL_Indexes_Model, TL_ThemePush_Model
from apps.lib.public import edit_data, get_uuid32, errors, check_obj, add_data, del_not_day30
from apps.models.system_model import TL_Email_Model, TL_Validation_Model
@sys_bp.route ('/connector',endpoint ='connector',methods =['GET','POST'])
@login_required
def connector ():
    OO000OOO00OOOO00O =TL_Connector_Model .query .filter ().first ()
    O0O0OO000O0OO0OO0 =TL_WebApp_Model .query .filter ().first ()
    if request .method =='POST':
        if request .form .get ('verify'):
            O00O000O0O0O0OOO0 =generate_token (request .form .get ('public_key'))[-52 :]
            O0O000O0O00O0OO00 =RSA .generate (1024 ,Random .new ().read )
            OO0O0O0O00O00O000 =O0O000O0O00O0OO00 .exportKey ().decode ('utf-8')
            O0O0OO00OOO0000O0 =O0O000O0O00O0OO00 .publickey ().exportKey ().decode ('utf-8')
            return edit_data (TL_WebApp_Form ,TL_WebApp_Model ,db ,O0O0OO000O0OO0OO0 .id ,{"private_code":O00O000O0O0O0OOO0 ,'public_pem':O0O0OO00OOO0000O0 ,'private_pem':OO0O0O0O00O00O000 })
        return edit_data (TL_Connector_Form ,TL_Connector_Model ,db ,OO000OOO00OOOO00O .id ,{"impower_code":get_uuid32 ()})
    O00O000O0O000O0O0 =TL_Connector_Form (data =dict (OO000OOO00OOOO00O ))
    OOO00OOO00O0O00O0 =TL_WebApp_Form (data =dict (O0O0OO000O0OO0OO0 ))
    return render_template ('system_template/connector.html',form =O00O000O0O000O0O0 ,form2 =OOO00OOO00O0O00O0 )
@sys_bp.route ('/tool',endpoint ='tool',methods =['GET'])
@login_required
def tool ():
    O0OO00OOOO0OOO000 =TL_Indexes_Form (data =dict (TL_Indexes_Model .query .filter_by ().first ()))
    return render_template ('system_template/tools.html',form ={'indexes':O0OO00OOOO0OOO000 })
@sys_bp.route ('/email_send',endpoint ='email_send',methods =['GET','POST'])
@login_required
@Verify_authorization
def email_send ():
    OO00OOOOO0O000000 =TL_Email_Form (request .form )
    if request .method =='POST':
        try :
            if OO00OOOOO0O000000 .validate ():
                OOOOO000O00OOOOOO =TL_Email_Model .query .first ()
                current_app .config .update (DEBUG =False ,MAIL_SERVER =OOOOO000O00OOOOOO .MAIL_SERVER ,MAIL_PROT =OOOOO000O00OOOOOO .MAIL_PROT ,MAIL_USE_TLS =True ,MAIL_USE_SSL =True if OOOOO000O00OOOOOO .MAIL_USE_SSL else False ,MAIL_USERNAME =OOOOO000O00OOOOOO .MAIL_USERNAME ,MAIL_PASSWORD =OOOOO000O00OOOOOO .MAIL_PASSWORD ,)
                OOO0OO00O0OO0000O =Message (OO00OOOOO0O000000 .email_title .data ,sender =OOOOO000O00OOOOOO .MAIL_USERNAME ,recipients =[OO00OOOOO0O000000 .email_addressee .data ])
                OOO0OO00O0OO0000O .html =OO00OOOOO0O000000 .email_content .data
                OOO0OOO0O0O0O0O00 =Mail (current_app )
                OOO0OOO0O0O0O0O00 .send (OOO0OO00O0OO0000O )
                return jsonify ({"status":0 ,'msg':'发送成功'})
            return jsonify ({"status":1 ,"msg":errors (OO00OOOOO0O000000 )})
        except :
            return jsonify ({"status":1 ,"msg":"发送错误,请确认配置正确!"})
    return render_template ('system_template/email.html',form =OO00OOOOO0O000000 )
@sys_bp.route ('/emptyCache',endpoint ='emptyCache',methods =['POST'])
@login_required
def emptyCache ():
    cache .clear ()
    del_not_day30 ('tl_visit_num')
    return jsonify ({"status":0 })
@sys_bp.route ('/validation_authorization',endpoint ='validation_authorization',methods =['GET'])
@login_required
def validation_authorization ():
    OO0OO000OO00OO0O0 =TL_Validation_Model .query .order_by (TL_Validation_Model .id .desc ()).filter_by ().first ()
    if OO0OO000OO00OO0O0 :
        try :
            O000OO0000O0O0000 =requests .post (base64 .b64decode (b'aHR0cDovL3d3dy50bGNtcy5uZXQvYXV0aGVudGljYXRpb24=').decode (),data ={'domain':request .host_url ,'auth_code':OO0OO000OO00OO0O0 .v_code })
            if O000OO0000O0O0000 .status_code ==200 and O000OO0000O0O0000 .json ()['status']==0 :
                return jsonify ({'status':0 })
            elif O000OO0000O0O0000 .status_code ==200 and O000OO0000O0O0000 .json ()['status']!=0 :
                return jsonify ({'status':1 ,'msg':O000OO0000O0O0000 .json ()['msg']})
        except :
            pass
        return jsonify ({'status':2 ,'msg':base64 .b64decode (b'5o6I5p2D5aSx6LSlLOi/nuaOpeaOiOadg+acjeWKoeWZqOWksei0pSE=').decode ()})
    return jsonify ({'status':-1 })
@sys_bp.route ('/tl_sys_validation_authorization',endpoint ='tl_sys_validation_authorization',methods =['SELECT'])
@login_required
def save_validation_authorization ():
    try :
        O0OOOOO0O0O0O0OO0 =request .form .get ('auth_code')
        O0OO0OO0OOOOO0000 =requests .post (base64 .b64decode (b'aHR0cDovL3d3dy50bGNtcy5uZXQvYXV0aGVudGljYXRpb24=').decode (),data ={'domain':request .host_url ,'auth_code':O0OOOOO0O0O0O0OO0 })
        try :
            if O0OO0OO0OOOOO0000 .status_code ==200 and O0OO0OO0OOOOO0000 .json ()['status']==0 :
                O00OOO00000O0O0O0 =TL_Validation_Model ()
                O00OOO00000O0O0O0 .set_attrs ({'v_code':O0OOOOO0O0O0O0OO0 })
                db .session .add (O00OOO00000O0O0O0 )
                db .session .commit ()
                return jsonify ({'status':0 ,'msg':base64 .b64decode (b'5oGt5Zac5oKoLOiOt+W+l1RM5a6Y5pa55o6I5p2D5oiQ5YqfIQ==').decode ()})
            elif O0OO0OO0OOOOO0000 .status_code ==200 and O0OO0OO0OOOOO0000 .json ()['status']!=0 :
                return jsonify ({'status':1 ,'msg':O0OO0OO0OOOOO0000 .json ()['msg']})
        except :
            db .session .rollback ()
            return jsonify ({'status':3 ,'msg':base64 .b64decode (b'5o6I5p2D5aSx6LSl5byC5bi4LOivt+iBlOezu+W8gOWPkeiAhSE=').decode ()})
    except :
        pass
    return jsonify ({'status':2 ,'msg':base64 .b64decode (b'5o6I5p2D5aSx6LSlLOi/nuaOpeaOiOadg+acjeWKoeWZqOWksei0pSE=').decode ()})
@sys_bp.route ('/indexes',endpoint ='indexes',methods =['POST','UPDATE'])
@login_required
def indexes ():
    O00O0O0O0OO0OOO0O =TL_Indexes_Form (request .form )
    try :
        O0OO000O0000O00OO =TL_Indexes_Model .query .filter_by ().first ()
        if O00O0O0O0OO0OOO0O .validate ()and not check_obj (O0OO000O0000O00OO ):
            O0OO000O0000O00OO .set_attrs (O00O0O0O0OO0OOO0O .data )
            db .session .commit ()
        else :
            return jsonify ({"status":1 ,"msg":errors (O00O0O0O0OO0OOO0O )})
    except :
        db .session .rollback ()
        return jsonify ({"status":1 ,"msg":errors (O00O0O0O0OO0OOO0O )})
    if request .method =='POST':
        OOOO00OO0OO00O0OO ={'User-Agent':'curl/7.12.1','Host':'data.zz.baidu.com','Content-Type':'text/plain'}
        OOOOO0OO0OO0O0O00 =TL_Content_Model .query .order_by (TL_Content_Model .id .desc ()).filter (TL_Content_Model .status ==1 ,TL_Content_Model .update_time <datetime .now ()).all ()[:int (O00O0O0O0OO0OOO0O .indexes_num .data )]
        OO00OO0OO0000OO00 =[f'{O00O0O0O0OO0OOO0O.indexes_design.data}'.replace ('[*tl-did*]',OO000000OOOO00O00 .uuid )for OO000000OOOO00O00 in OOOOO0OO0OO0O0O00 ]
        if not len (OO00OO0OO0000OO00 ):return jsonify ({'status':1 ,'msg':'未获取到参数,请添加内容'})
        OO000000O00O0OO00 =requests .post (O00O0O0O0OO0OOO0O .push_address .data ,data ='\n'.join (OO00OO0OO0000OO00 ),headers =OOOO00OO0OO00O0OO )
        if OO000000O00O0OO00 .status_code ==200 :
            return jsonify ({'status':0 ,'msg':'百度索引提交成功!'})
        return jsonify ({'status':4 ,'msg':f'提交失败{OO000000O00O0OO00.json()["message"]}({OO000000O00O0OO00.json()["error"]})'})
    return jsonify ({'status':0 ,'msg':'保存成功'})
@sys_bp.route ('/templates_theme',endpoint ='templates_theme',methods =['GET','POST','UNLOAD'])
@login_required
def templates_theme ():
    if request .method =='POST':
        O0OOOOO000OO0O00O =request .form .get ('theme_id','')
        O0O0O000OO00OO0OO =TL_ThemePush_Model .query .filter_by (uuid =O0OOOOO000OO0O00O ).first ()
        if check_obj (O0O0O000OO00OO0OO ):pass
        O0OOO0O0OO000OO00 =TL_ThemePush_Model .query .filter ().all ()
        for O00O0OO0OOO00OO0O in O0OOO0O0OO000OO00 :O00O0OO0OOO00OO0O .set_attrs ({'is_current':0 })
        try :
            db .session .commit ()
        except :
            db .session .rollback ()
            return jsonify ({'status':1 ,'msg':'应用模板失败'})
        try :
            O0O0O000OO00OO0OO .set_attrs ({'is_current':1 })
            db .session .commit ()
        except :
            db .session .rollback ()
            return jsonify ({'status':1 ,'msg':'应用模板失败'})
        cache .delete ('current_theme')
        return jsonify ({'status':0 })
    elif request .method =='UNLOAD':
        O0OOOOO000OO0O00O =request .form .get ('theme_id','')
        O0O0O000OO00OO0OO =TL_ThemePush_Model .query .filter_by (uuid =O0OOOOO000OO0O00O ).first ()
        if check_obj (O0O0O000OO00OO0OO ):pass
        db .session .delete (O0O0O000OO00OO0OO )
        try :
            db .session .commit ()
        except :
            db .session .rollback ()
            return jsonify ({'status':1 ,'msg':'卸载模板失败'})
        return jsonify ({'status':0 ,'msg':'卸载模板成功'})
    O0O0O000OO00OO0OO =TL_ThemePush_Model .query .filter_by (is_current =1 ).first ()
    O0OOO0O0OO000OO00 =TL_ThemePush_Model .query .filter ().all ()
    OO00OO0OO0OOO000O =f'{os.getcwd()}/apps/templates/web_template'.replace ('\\','/')
    try :
        with open (f'{OO00OO0OO0OOO000O}/{O0O0O000OO00OO0OO.identifier}/info.json','r',encoding ='utf-8')as O0OOO0OOO0O0OO00O :
            OOOO000O00O000OOO =json .loads (O0OOO0OOO0O0OO00O .read ())
    except :
        return abort (404 )
    OOOO000O00O000OOO .update ({'theme_id':O0O0O000OO00OO0OO .uuid })
    OOO0O0OO0OOOOOO0O ={'info':OOOO000O00O000OOO }
    OO0OO0O0O0OOOOOOO =[]
    for O00O0OO0OOO00OO0O in O0OOO0O0OO000OO00 :
        try :
            if os .path .isfile (f'{OO00OO0OO0OOO000O}/{O00O0OO0OOO00OO0O.identifier}/info.json'):
                with open (f'{OO00OO0OO0OOO000O}/{O00O0OO0OOO00OO0O.identifier}/info.json','r',encoding ='utf-8')as O0OOO0OOO0O0OO00O :
                    O00O00O000O0000OO =json .loads (O0OOO0OOO0O0OO00O .read ())
                    O00O00O000O0000OO .update ({'theme_id':O00O0OO0OOO00OO0O .uuid })
                    OO0OO0O0O0OOOOOOO .append (O00O00O000O0000OO )
        except :pass
    return render_template ('system_template/templates_theme.html',current_theme =OOO0O0OO0OOOOOO0O ,themes =OO0OO0O0O0OOOOOOO )
@sys_bp.route ('/theme_push',endpoint ='theme_push',methods =['GET','POST'])
@login_required
def theme_push ():
    if request .method =='POST':
        return add_data (TL_ThemePush_Model ,TL_ThemePush_Form ,db )
    return render_template ('system_template/theme_push.html')
